﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyResKit;

namespace MyFramework.UIKit
{
	public class UIPanel : MonoBehaviour {
		
		protected static Dictionary<string,UIPanel> mPanels = new Dictionary<string,UIPanel>();

		public static void OpenPanel<TPanel>(UILayer uiLayer = UILayer.Common) where TPanel : UIPanel
		{
			var panelName = typeof(TPanel).ToString ();
			var splitedPanelName = panelName.Split (new []{ '.' });
			panelName = splitedPanelName [splitedPanelName.Length - 1];

			if (mPanels.ContainsKey (panelName))
			{
				mPanels [panelName].Open ();
			}
			else
			{
				var panelLoader = new ResLoader ();
				var panelTrans = Instantiate (panelLoader.Load<GameObject> (panelName)).transform as RectTransform;

				switch (uiLayer)
				{
					case UILayer.Common:
						panelTrans.SetParent (UIRoot.Common);
						break;
					case UILayer.Bottom:
						panelTrans.SetParent (UIRoot.Bottom);
						break;
					case UILayer.Top:
						panelTrans.SetParent (UIRoot.Top);
						break;
				}

				panelTrans.anchorMin = Vector2.zero;
				panelTrans.anchorMax = Vector2.one;
				panelTrans.anchoredPosition = Vector2.zero;
				panelTrans.name = panelName;
				var panel = panelTrans.GetComponent<TPanel> ();
				mPanels.Add (panelTrans.name, panel);

				panel.mPanelLoader = panelLoader;
				panel.Open ();
			}
		}

		private ResLoader mPanelLoader;

		public void Init()
		{
			mPanels.Add (gameObject.name, this);
		}

		public void Open()
		{
			gameObject.SetActive (true);
		}

		public void Close()
		{
			mPanels.Remove (this.name);
			Destroy (gameObject);
			mPanelLoader.UnloadAll ();
		}
	}
}